/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.zonasoft.dao;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author william
 */
public class JPAGenericDAO<T> extends AbstractGenericDAO<T> {

    private EntityManagerFactory emf;

    public JPAGenericDAO(Class<T> c) {
        super(c);
    }

    private EntityManager getEntityManager() {
        if (this.emf == null) {
            this.emf = Persistence.createEntityManagerFactory("zonificacionWebPU");
            this.emf.close();
        }
        return this.emf.createEntityManager();
    }

    public boolean save(T t) {
        EntityManager em = this.getEntityManager();
        em.getTransaction().begin();
        try {
            em.merge(t);
            em.getTransaction().commit();
            em.close();
            
            return true;
        }catch(Exception e){
            em.getTransaction().rollback();
            em.close();
            return false;
        }
    }

    public T getById(Long id) {
        return (T) this.getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        EntityManager em = this.getEntityManager();
        Query q = em.createQuery("SELECT c FROM " + entityClass.getSimpleName() + " c");
        return q.getResultList();
    }

    public List<T> get(String query) {
        EntityManager em = this.getEntityManager();
        em.getTransaction().begin();
        try {
            Query q = em.createQuery(query);
            List<T> results = q.getResultList();
            em.getTransaction().commit();
            em.close();
            return results;
        } catch (Exception e) {
            em.getTransaction().rollback();
            em.close();
            return null;
        }
    }

    public void executeQuery(String query) {
        EntityManager em = this.getEntityManager();
        em.getTransaction().begin();
        try {
            int i = em.createQuery(query).executeUpdate();
            em.getTransaction().commit();
            em.close();
        } catch (Exception e) {
            em.getTransaction().rollback();
            em.close();
        }
    }

      public boolean remove(Long id) {
        EntityManager em = this.getEntityManager();
        em.getTransaction().begin();
        T t = em.find(entityClass, id);
        try {
            em.remove(t);
            em.getTransaction().commit();
            em.close();
            return true;
        }catch(Exception e){
            e.printStackTrace();
            em.getTransaction().rollback();
            em.close();
            return false;
        }
    }
}
